package site.jlopen.secret.service.intf;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import site.jlopen.secret.client.SecretClientHttp;
import site.jlopen.secret.client.SecretClientHttpErrorCode;
import site.jlopen.secret.client.SecretReqUrl;
import site.jlopen.secret.common.SecretClientResponse;
import site.jlopen.secret.common.SecretReqBaseForm;
import site.jlopen.secret.config.SecretClientProperties;

public class SecretAuthService {
	private final Logger logger = LoggerFactory.getLogger(getClass());

	private final SecretClientProperties clientProperties;
	
	public SecretAuthService(SecretClientProperties clientProperties) {
		this.clientProperties = clientProperties;
	}

	public void login() {
		if(clientProperties.isEnable()) {
			SecretClientHttp<String> clientRequest = new SecretClientHttp<String>(clientProperties);
			Map<String, Object> form = new SecretReqBaseForm<Object>()
					.appId(clientProperties.getAppId())
					.add("username", clientProperties.getAppId())
					.add("password", clientProperties.getAppSecret());
			SecretClientResponse<String>  res = clientRequest.execute(SecretReqUrl.AUTH_URL, form);
			if(res.getStatus() == SecretClientHttpErrorCode.SUCCESS) {
				clientProperties.setToken(res.getData());
				logger.info("secret sdk 登录成功");
			}else {
				logger.error("secret sdk 登录失败：{}", res.getData());
			}
		}
	}
}
